package com.njitt.bysj.config;

import com.njitt.bysj.bean.DeptBean;
import com.njitt.bysj.bean.EmpBean;
import com.njitt.bysj.bean.LoginBean;
import com.njitt.bysj.mapper.DeptBeanMapper;
import com.njitt.bysj.mapper.PermissionBeanMapper;
import com.njitt.bysj.mapper.RoleBeanMapper;
import com.njitt.bysj.model.EmpModel;
import com.njitt.bysj.srevice.EmpService;
import com.njitt.bysj.srevice.LoginService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Set;

/**
 * @description:
 * @author: wyj
 * @time: 2022/3/18 23:53
 */
public class UserRealm extends AuthorizingRealm {
    @Resource
    private LoginService loginService;
    @Resource
    private DeptBeanMapper mapper;
    @Resource
    private EmpService empService;
    @Resource
    private RoleBeanMapper roleMapper;
    @Resource
    private PermissionBeanMapper permissionMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        /**
         * @description:
         * @return:  * @param principalCollection  参数代表可以获取当前登录对象
         * @author: 获取授权
         * @time: 2022/3/20 20:16
         */
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        EmpModel emp = (EmpModel) principalCollection.iterator().next();
        Set<String> strings = roleMapper.queryRoleNameByEmpId(emp.getId());
        info.setRoles(strings);
        return info;
    }


    /**
     * @description: 认证 shiro来做登录
     * @return: * @param null
     * @author: wyj
     * @time: 2022/3/20 20:06
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        token.setRememberMe(true);
        LoginBean bean = loginService.loginUser(token.getUsername());
        EmpModel emp = empService.findEmpByLoginId(bean.getId());
        Set<String> roles = roleMapper.queryRoleNameByEmpId(emp.getId());
        emp.setRoles(new ArrayList<>(roles));
        return new SimpleAuthenticationInfo(emp, bean.getPassword(), getName());
    }

    @Override
    public String getName() {
        return "userRealm";
    }
}
